﻿
/// <summary>
/// Helper class to implement some user authorisation 
/// </summary>
public class AuthorizeUser
{
    #region Properties

    private string _refuseMessage;
    public string RefuseMessage
    {
        get { return _refuseMessage; }
    }

    private bool _isAuthorized;
    public bool IsAuthorized
    {
        get { return _isAuthorized; }
    }
    
    private string _user;

    #endregion

    #region C'tor

    public AuthorizeUser(string user, string pwd)
	{
        _user = user;
        _isAuthorized = string.IsNullOrEmpty(user) == false && user.Length > 4;
        if (IsAuthorized == false)
            _refuseMessage = "Invalid User!";
        else
        {
            if (ValidatePwd(pwd))
            {
                _isAuthorized = false;
                _refuseMessage = "User " + user + " is not authentified!";
            }
        }
    }
    #endregion

    #region Password validation

    /// <summary>
/// Here you can implement desired authentication mechanism. 
/// $$ This is a dummy one $$
/// </summary>
/// <param name="pwd">String representing password</param>
/// <returns>True if not valid</returns>
    private bool ValidatePwd(string pwd)
    {
        int n = 0;
        try
        {
            if (pwd != null)
            {
                byte[] bytes = HexToByte(pwd);
                for (int i = 0; i < bytes.Length; i++)
                    n += (int)bytes[i];
            }
        }
        catch
        {
        }

        return n != 454;
    }

    public static byte[] HexToByte(string s)
    {
        if (string.IsNullOrEmpty(s))
            s = "??";

        byte[] b = new byte[s.Length / 2];
        for (int i = 0; i < b.Length; i++)
            b[i] = (byte)int.Parse(s.Substring(2 * i, 2), System.Globalization.NumberStyles.HexNumber);
        return b;
    }

    #endregion
}
